﻿using CmccTool.KPI.Services;
using CmccTool.Services;
using MiniExcelLibs;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace CmccTool.KPI.View
{
    public partial class KpiImport : UserControl
    {
        private readonly BackgroundWorker worker = new();
        private DateTime lastImportDate;
        public KpiImport()
        {
            InitializeComponent();
            // 启用进度报告和取消支持
            worker.WorkerReportsProgress = true;
            worker.WorkerSupportsCancellation = true;
            // 订阅事件
            worker.DoWork += Worker_DoWork;
            worker.ProgressChanged += Worker_ProgressChanged;
            worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
            // 显示数据库路径
            //txtLog.AppendText(AppConfig.dbPath + Environment.NewLine);
        }

        private void BtStart_Click(object sender, EventArgs e)
        {
            List<string> files = FileHelper.SelectMultipleFiles("Zip或csv|*.zip;*.csv");

            lastImportDate = DateTime.Now;

            foreach (string file in files)
            {
                txtLog.AppendText($"{DateTime.Now}: {file}{Environment.NewLine}");
            }
            txtLog.AppendText($"{DateTime.Now}: 共计[{files.Count}]个文件{Environment.NewLine}");
            //
            if (!worker.IsBusy && files.Count != 0)
            {
                progressBar.Value = 0; // 重置进度条
                progressBar.Maximum = files.Count;
                worker.RunWorkerAsync(files);

            }
            else if(worker.IsBusy)
            {
                txtLog.AppendText($"{DateTime.Now}: 繁忙");
            }
            else if(files.Count == 0)
            {
                txtLog.AppendText($"{DateTime.Now}: 没有可处理文件{Environment.NewLine}");
            }
        }

        private void Worker_DoWork(object? sender, DoWorkEventArgs e)
        {
            using var db = KpiImpHelper.KpiDbChh();

            if (db == null)
            {
                e.Result = "数据库连接失败";
                return;
            }

            if (e.Argument is not List<string> files || files.Count == 0) { e.Result = "没有可处理文件"; return; }

            /*
            int totalImported = KpiImpHelper.ImportFilesToDatabase(files, db, progress =>
            {
                worker.ReportProgress(progress);
            });
            */

            // 新增逐文件导入逻辑
            int totalImported = 0;
            int fileNo = 0;
            int fileCount = files.Count;
            foreach (var file in files)
            {
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
                try
                {
                    int importedCount = KpiImpHelper.RecursiveImportFile(file, db, progress =>
                    {
                        fileNo += 1;
                        txtLog.Invoke(
                               () => txtLog.AppendText($"{DateTime.Now}: [ {fileNo} / {fileCount} ] : {file}")
                       );

                        worker.ReportProgress(progress); // 每处理一个文件报告一次进度
                    });

                    txtLog.Invoke(
                           () => txtLog.AppendText($"- 成功读取 {importedCount} (耗时 {(DateTime.Now-lastImportDate).ToString()}){Environment.NewLine}")
                        );

                    lastImportDate = DateTime.Now;
                    totalImported += importedCount;
                }
                catch (Exception ex)
                {
                    e.Result = $"导入文件 {file} 时出错: {ex.Message}";
                    return;
                }
            }

            db.Close();


            e.Result = $"成功导入{totalImported}条数据";
        }

        private void Worker_ProgressChanged(object? sender, ProgressChangedEventArgs e)
        {
            progressBar.Value += e.ProgressPercentage; // 更新进度条
            double percentage = (progressBar.Maximum != 0)
                ? progressBar.Value * 100.0 / progressBar.Maximum
                : 0;
            labelStatus.Text = $"{percentage:F2}%({progressBar.Value}/{progressBar.Maximum})";
        }

        private void Worker_RunWorkerCompleted(object? sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
                MessageBox.Show("操作已取消");
            else if (e.Error != null)
                MessageBox.Show($"错误: {e.Error.Message}");
            else
                MessageBox.Show(e.Result?.ToString()); // 显示结果
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            worker.CancelAsync(); // 请求取消
        }

        private void BtnKpiCheck_Click(object sender, EventArgs e)
        {

            var sql = KpiCheck.GenerateSql(AppConfig.KpiCheckConfigs);

            // 执行查询
            KpiQuertHelper KQ = new();
            txtLog.AppendText($"{DateTime.Now}: 开始统计，期间可能存在卡顿，请耐心等待，卡顿时间不超过1min。{Environment.NewLine}");
            txtLog.AppendText($"{DateTime.Now}: 查询近一年数据。{Environment.NewLine}");
            var dt = KQ.QueryDataBysql(sql);

            #region 检查数据完整性
            // 检查数据完整性
            string dateSta = string.Empty;
            string dataEnd ;
            bool isLost = false;
            for (var j = 1; j < dt.Columns.Count; j++)
            {
                var dataRange = string.Empty;
                string lastDate = string.Empty;
                
                for (var i = dt.Rows.Count; i >0; i--)
                {
                    
                    var row = dt.Rows[i-1];
                    if (row[j].ToString() == "0" && isLost == false)
                    {
                        isLost = true;
                        if (i == dt.Rows.Count)
                        {
                            dateSta = row[0].ToString() ?? $"row{i}";
                        }
                        else
                        {
                            dateSta = DateTime.Parse(lastDate).AddDays(1).ToString("yyyy-MM-dd");
                        }
                            
                    }
                    else if (row[j].ToString() != "0" && isLost == true)
                    {
                        isLost = false;
                        dataEnd =  DateTime.Parse(row[0].ToString() ?? $"NullRow{i}").AddDays(-1).ToString("yyyy-MM-dd");
                        dataRange += $"{Environment.NewLine}        {dateSta} ~ {dataEnd};";
                    }
                    if (i != dt.Rows.Count) {  lastDate = row[0].ToString() ?? $"row{i}"; }
                }

                if(isLost)
                {
                    dataEnd = lastDate;
                    dataRange += $"{dateSta} ~ {dataEnd};";
                }

                if (!string.IsNullOrEmpty(dataRange))
                {
                    txtLog.AppendText($"{DateTime.Now}: {dt.Columns[j].ColumnName} 存在数据缺失，缺失时间段：{dataRange}{Environment.NewLine}");
                }
            }
            #endregion

            txtLog.AppendText($"{DateTime.Now}: 共计{dt.Rows.Count}条。{Environment.NewLine}");

            string f = Path.Combine(AppConfig.GetSafeAppDataPath(), "exp", "kpiCheck_" + DateTime.Now.ToString("yyyy-MM-dd hh_mm_ss") + ".xlsx");
            txtLog.AppendText($"{DateTime.Now}: 导出{f}{Environment.NewLine}");
            MiniExcel.SaveAs(f, dt);
            txtLog.AppendText($"{DateTime.Now}: 导出完成{Environment.NewLine}");
        }
    }
}
